package org.example.springboot.dao.impl;

import org.example.springboot.dao.ProductDAO;
import org.example.springboot.entity.Product;
import org.example.springboot.util.JDBCUtils;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

public class ProductDAOImpl implements ProductDAO {

    @Override
    public List<Product> getAllProducts() {
        return JDBCUtils.executeQuery(Product.class, "SELECT * FROM s_product");
    }

    @Override
    public Product getProductById(String id) {
        List<Product> products = JDBCUtils.executeQuery(Product.class, "SELECT * FROM s_product WHERE id = ?", id);
        return products.isEmpty() ? null : products.get(0);
    }

    @Override
    public int addProduct(Product product) {
        product.setCreate_time(Timestamp.valueOf(LocalDateTime.now()));
        return JDBCUtils.executeUpdate(
                "INSERT INTO s_product (id, product_name, product_image, price, product_type, product_desc, create_time, product_brand) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                product.getId(),
                product.getProduct_name(),
                product.getProduct_image(),
                product.getPrice(),
                product.getProduct_type(),
                product.getProduct_desc(),
                product.getCreate_time(),
                product.getProduct_brand()
        );
    }

    @Override
    public int updateProduct(Product product) {
        return JDBCUtils.executeUpdate(
                "UPDATE s_product SET product_name = ?, product_image = ?, price = ?, product_type = ?, product_desc = ?, product_brand = ? WHERE id = ?",
                product.getProduct_name(),
                product.getProduct_image(),
                product.getPrice(),
                product.getProduct_type(),
                product.getProduct_desc(),
                product.getProduct_brand(),
                product.getId()
        );
    }

    @Override
    public int deleteProduct(String id) {
        return JDBCUtils.executeUpdate("DELETE FROM s_product WHERE id = ?", id);
    }

    @Override
    public Integer selectProductCount() {
        return JDBCUtils.executeCount("SELECT COUNT(*) FROM s_product");
    }

    @Override
    public List<Product> selectProductLimits(int start, int row) {
        return JDBCUtils.executeQuery(Product.class, "SELECT * FROM s_product LIMIT ?, ?", start, row);
    }
}